package log

import (
	"encoding/json"
	"net/http"
	"yunzhan/log-server/internal/websocket"

	"github.com/zeromicro/go-zero/rest/httpx"
	"yunzhan/log-server/internal/logic/log"
	"yunzhan/log-server/internal/svc"
	"yunzhan/log-server/internal/types"
)

var cm = websocket.NewConnectionManager()

func SocketHandler() http.HandlerFunc {
	return websocket.WebSocketHandler(cm)
}

func RecordLogHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.RecordLogRequest
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		l := log.NewRecordLogLogic(r.Context(), svcCtx)
		resp, err := l.RecordLog(&req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
			// Broadcast log to WebSocket clients
			logEntry := types.LogEntry{
				Component: req.Component,
				Service:   req.Service,
				Message:   req.Message,
				Timestamp: "Now()",
			}
			message, _ := json.Marshal(logEntry)
			cm.Broadcast(message)

			httpx.OkJson(w, resp)
		}
	}
}
